package de.szut.scene.helper;

import android.app.Activity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.gson.Gson;
import de.szut.database.DatabaseHelper;
import de.szut.entity.Country;
import de.szut.entity.OperatingSystem;
import de.szut.interfaces.IResearch;
import de.szut.logic.Logic;
import de.szut.logic.ModifierStore;
import de.szut.util.ModifierType;
import de.szut.util.OperatingSystemName;
import de.szut.util.Settings;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: nbothmer
 * Date: 29.10.13
 * Time: 11:32
 * To change this template use File | Settings | File Templates.
 */
public class StorageHelper {

    private static StorageHelper instance = null;
    private Activity activity;
    private DatabaseHelper dbHelper;

    public StorageHelper(Activity activity, DatabaseHelper dbHelper) {
        this.activity = activity;
        this.dbHelper = dbHelper;

    }

    public static StorageHelper getInstance(Activity activity, DatabaseHelper dbHelper) {
        if (instance == null) {
            instance = new StorageHelper(activity, dbHelper);
        }
        return instance;
    }

    public boolean pixelMapsAreNotCreated() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        boolean mapIsCreated = prefs.getBoolean(Settings.PIXELMAP_KEY_PREFS, true);
        return mapIsCreated;
    }

    public void pixelMapsAreCreated(HashMap<String, ArrayList<String>> countryPixelMap, HashMap<String, String> centerPoints) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        prefs.edit().putBoolean(Settings.PIXELMAP_KEY_PREFS, false).commit();
        savePixelMapToPreferences(countryPixelMap);
        saveCountryCenterPointsToPreferences(centerPoints);
    }

    public void savePixelMapToPreferences(HashMap<String, ArrayList<String>> countryPixelMap) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        for (String s : countryPixelMap.keySet()) {
            Set<String> set = new HashSet<String>(countryPixelMap.get(s));
            editor.putStringSet(s,set);
            editor.commit();
        }
    }
    public void saveCountryCenterPointsToPreferences(HashMap<String,String> centerPoints) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        for (String s : centerPoints.keySet()) {
            editor.putString(Settings.CENTER_POINTS_PREFS + s,centerPoints.get(s));
            editor.commit();
        }
    }
    public void loadCountryCenterPointsFromPreferences(HashMap<String,String> countryCenterPoints) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        ModifierStore modifierStore = Logic.getInstance(activity).getModifierStore();
        modifierStore.loadAllCountries();
        for (Country c : modifierStore.allCountries) {
            String value = prefs.getString(Settings.CENTER_POINTS_PREFS + c.getName(), "");
            countryCenterPoints.put(c.getName(),value);
        }

    }

    public void loadPixelMapFromPreferences(HashMap<String, ArrayList<String>> countryPixelMap) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        ModifierStore modifierStore = Logic.getInstance(activity).getModifierStore();
        modifierStore.loadAllCountries();
        for (Country c : modifierStore.allCountries) {
            Set<String> set = prefs.getStringSet(c.getName(), new HashSet<String>());
            countryPixelMap.put(c.getName(), new ArrayList<String>(set));
        }

    }

    public boolean gotNonSavedGameState(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        boolean gotSavedGameState = prefs.getBoolean(Settings.GAME_STATE_SAVED, true);
        return gotSavedGameState;
    }

    private void gameStateIsSaved(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        prefs.edit().putBoolean(Settings.GAME_STATE_SAVED, false).commit();
    }

    public void saveGameState(Logic logic){
        this.saveNonInfectedCountriesToPrefs(logic);
        this.saveInfectedCountriesToPrefs(logic);
        this.saveControlledCountriesToPrefs(logic);
        this.saveOperatinSystemsToPrefs(logic);
        this.saveResearchesToPrefs(logic);
        this.saveModifierValuesToPrefs(logic);
        this.gameStateIsSaved();
    }

    public void loadGameState(Logic logic){
        this.loadNonInfectedCountriesFromPrefs(logic);
        this.loadInfectedCountriesFromPrefs(logic);
        this.loadControlledCountriesFromPrefs(logic);
        this.loadOperatingSystemsFromPrefs(logic);
        this.loadResearchesFromPrefs(logic);
        this.loadModifierValueFromPrefs(logic);
    }

    private void saveInfectedCountriesToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getInfectedCountries().isEmpty()) {
            for (Country c : logic.getInfectedCountries()) {
                Gson gson = new Gson();
                String countryJson = gson.toJson(c);
                editor.putString(Settings.SAVE_INFECTED_COUNTRY_PREFS + Integer.toString(c.getColor()), countryJson);
                editor.commit();
            }
        }
    }

    private void saveNonInfectedCountriesToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getNonInfectedCountries().isEmpty()) {
            for (Country c : logic.getNonInfectedCountries()) {
                Gson gson = new Gson();
                String countryJson = gson.toJson(c);
                editor.putString(Settings.SAVE_NONINFECTED_COUNTRY_PREFS + Integer.toString(c.getColor()), countryJson);
                editor.commit();
            }
        }
    }

    private void saveControlledCountriesToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getControlledCountries().isEmpty()) {
            for (Country c : logic.getControlledCountries()) {
                Gson gson = new Gson();
                String countryJson = gson.toJson(c);
                editor.putString(Settings.SAVE_CONTROLLED_COUNTRY_PREFS + Integer.toString(c.getColor()), countryJson);
                editor.commit();
            }
        }
    }

    private void saveResearchesToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getResearches().isEmpty()) {
            for (IResearch r : logic.getResearches()) {
                Gson gson = new Gson();
                String researchJson = gson.toJson(r);
                editor.putString(Settings.SAVE_RESEARCH_PREFS + String.valueOf(r.getOperatingSystem()), researchJson);
                editor.commit();
            }
        }
    }

    private void saveOperatinSystemsToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getOperatingSystemList().isEmpty()) {
            for (OperatingSystem op : logic.getOperatingSystemList()) {
                Gson gson = new Gson();
                String opJson = gson.toJson(op);
                editor.putString(Settings.SAVE_OP_PREFS + String.valueOf(op.getOperatingSystemName()), opJson);
                editor.commit();
            }
        }
    }

    private void saveModifierValuesToPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        SharedPreferences.Editor editor = prefs.edit();
        if (!logic.getModifierValues().isEmpty()) {
            for (ModifierType type : logic.getModifierValues().keySet()) {
                editor.putString(Settings.SAVE_MODIFIER_PREFS + type.toString(), type.toString() + ";" + logic.getModifierValues().get(type).toString());
                editor.commit();
            }
        }
    }

    private void loadModifierValueFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        HashMap<ModifierType, Double> modiValues = new HashMap<ModifierType, Double>();
        ArrayList<String> types = new ArrayList<String>();
        String deathRate = prefs.getString(Settings.SAVE_MODIFIER_PREFS + ModifierType.DEATH_RATE, "");
        String spreadRate = prefs.getString(Settings.SAVE_MODIFIER_PREFS + ModifierType.SPREAD_RATE, "");
        String resistanceRate = prefs.getString(Settings.SAVE_MODIFIER_PREFS + ModifierType.RESISTANCE_RATE, "");
        types.add(deathRate);
        types.add(spreadRate);
        types.add(resistanceRate);
        for (String s : types) {
            StringTokenizer tokenizer = new StringTokenizer(s, ";");
            String modiType = tokenizer.nextToken();
            double modiValue = Double.parseDouble(tokenizer.nextToken());
            if (modiType == ModifierType.DEATH_RATE.toString()) {
                modiValues.put(ModifierType.DEATH_RATE, modiValue);
            }
            if (modiType == ModifierType.RESISTANCE_RATE.toString()) {
                modiValues.put(ModifierType.RESISTANCE_RATE, modiValue);
            }
            if (modiType == ModifierType.SPREAD_RATE.toString()) {
                modiValues.put(ModifierType.SPREAD_RATE, modiValue);
            }

        }
        logic.setModifierValues(modiValues);

    }

    private void loadOperatingSystemsFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        List<OperatingSystem> operatingSystems = new ArrayList<OperatingSystem>();
        Gson linuxGson = new Gson();
        Gson winGson = new Gson();
        Gson macGson = new Gson();
        String linuxJson = prefs.getString(Settings.SAVE_OP_PREFS + String.valueOf(OperatingSystemName.LINUX), "");
        String winJson = prefs.getString(Settings.SAVE_OP_PREFS + String.valueOf(OperatingSystemName.WINDOWS), "");
        String macJson = prefs.getString(Settings.SAVE_OP_PREFS + String.valueOf(OperatingSystemName.MAC), "");
        OperatingSystem linux = linuxGson.fromJson(linuxJson, OperatingSystem.class);
        OperatingSystem windows = winGson.fromJson(winJson, OperatingSystem.class);
        OperatingSystem mac = macGson.fromJson(macJson, OperatingSystem.class);
        operatingSystems.add(linux);
        operatingSystems.add(windows);
        operatingSystems.add(mac);
        logic.setOperatingSystemList(operatingSystems);
    }

    private void loadResearchesFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        List<IResearch> researches = new ArrayList<IResearch>();
        Gson linuxGson = new Gson();
        Gson winGson = new Gson();
        Gson macGson = new Gson();
        String linuxJson = prefs.getString(Settings.SAVE_RESEARCH_PREFS + String.valueOf(OperatingSystemName.LINUX), "");
        String winJson = prefs.getString(Settings.SAVE_RESEARCH_PREFS + String.valueOf(OperatingSystemName.WINDOWS), "");
        String macJson = prefs.getString(Settings.SAVE_RESEARCH_PREFS + String.valueOf(OperatingSystemName.MAC), "");
        IResearch linux = linuxGson.fromJson(linuxJson, IResearch.class);
        IResearch windows = winGson.fromJson(winJson, IResearch.class);
        IResearch mac = macGson.fromJson(macJson, IResearch.class);
        researches.add(linux);
        researches.add(windows);
        researches.add(mac);
        logic.setResearches(researches);

    }

    private void loadInfectedCountriesFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        List<Country> infectedCountries = new ArrayList<Country>();
        if (dbHelper.getCountryDao().getCountries().isEmpty()) {
            dbHelper.getCountryDao().loadAllCountries();
        }
        for (Country c : dbHelper.getCountryDao().getCountries()) {
            Gson gson = new Gson();
            String countryJson = prefs.getString(Settings.SAVE_INFECTED_COUNTRY_PREFS + Integer.toString(c.getColor()), "");
            if (countryJson != null) {
                Country country = gson.fromJson(countryJson, Country.class);
                infectedCountries.add(country);
            }
        }
        logic.setInfectedCountries(infectedCountries);

    }

    private void loadNonInfectedCountriesFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        List<Country> notInfectedCountries = new ArrayList<Country>();
        if (dbHelper.getCountryDao().getCountries().isEmpty()) {
            dbHelper.getCountryDao().loadAllCountries();
        }
        for (Country c : dbHelper.getCountryDao().getCountries()) {
            Gson gson = new Gson();
            String countryJson = prefs.getString(Settings.SAVE_NONINFECTED_COUNTRY_PREFS + Integer.toString(c.getColor()), "");
            if (countryJson != null) {
                Country country = gson.fromJson(countryJson, Country.class);
                notInfectedCountries.add(country);
            }
        }
        logic.setInfectedCountries(notInfectedCountries);
    }

    private void loadControlledCountriesFromPrefs(Logic logic) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
        List<Country> controlledCountries = new ArrayList<Country>();
        if (dbHelper.getCountryDao().getCountries().isEmpty()) {
            dbHelper.getCountryDao().loadAllCountries();
        }
        for (Country c : dbHelper.getCountryDao().getCountries()) {
            Gson gson = new Gson();
            String countryJson = prefs.getString(Settings.SAVE_CONTROLLED_COUNTRY_PREFS + Integer.toString(c.getColor()), "");
            if (countryJson != null) {
                Country country = gson.fromJson(countryJson, Country.class);
                controlledCountries.add(country);
            }
        }
        logic.setInfectedCountries(controlledCountries);
    }
}
